package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.dto.OrdersPageDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }


    /**
     * 订单查询
     */
    @GetMapping("/userPage")
    public R<Page> userPage(Integer page, Integer pageSize) {
        //分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);

        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //执行分页查询
        orderService.page(pageInfo, queryWrapper);


        //查询订单详细 ↓ --------------------------------------------------------------

        //获取订单基本信息
        List<Orders> records = pageInfo.getRecords();
        if (records.size() <= 0) {
            return R.success(pageInfo);
        }

        //获取订单id集合
        Set<Long> ordersId = records.stream().map(orders -> orders.getId()).collect(Collectors.toSet());
        //通过订单id集合查询订单详情
        LambdaQueryWrapper<OrderDetail> detailQueryWrapper = new LambdaQueryWrapper<>();
        detailQueryWrapper.in(OrderDetail::getOrderId, ordersId);
        List<OrderDetail> orderDetails = orderDetailService.list(detailQueryWrapper);

        //循环遍历给每一个订单设置对应的订单详情
        ArrayList<OrdersDto> ordersDtoList = new ArrayList<>();
        for (Orders orders : records) {
            //获取当前订单对应的订单详情
            List<OrderDetail> details = orderDetails.stream().filter(orderDetail -> orderDetail.getOrderId().equals(orders.getId())).collect(Collectors.toList());

            //将基本的订单信息、订单详情信息封装成ordersDto
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);
            ordersDto.setOrderDetails(details);

            //将ordersDto添加到ordersDtoList集合
            ordersDtoList.add(ordersDto);
        }


        //将 分页数据 和 ordersDtoList 封装到 dtoPageInfo
        Page<OrdersDto> dtoPageInfo = new Page<>();
        BeanUtils.copyProperties(pageInfo, dtoPageInfo);
        dtoPageInfo.setRecords(ordersDtoList);

        return R.success(dtoPageInfo);
    }

    /**
     * 管理端订单页面分页查询
     * @param ordersPageDto
     * @return
     */
    @GetMapping("/page")
    public R page(OrdersPageDto ordersPageDto) {
        //分页构造器
        Page<Orders> pageInfo = new Page<>(ordersPageDto.getPage(), ordersPageDto.getPageSize());

        //添加构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        //订单号的模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(ordersPageDto.getNumber()), Orders::getNumber, ordersPageDto.getNumber());

        //开始时间、结束时间范围查询
        boolean condition = ordersPageDto.getBeginTime() != null && ordersPageDto.getEndTime() != null;
        LocalDateTime beginTime = ordersPageDto.getBeginTime();
        LocalDateTime endTime = ordersPageDto.getEndTime();
        queryWrapper.between(condition, Orders::getOrderTime, beginTime, endTime);

        //排序规则 "OrderTime 下单时间" 倒序
        queryWrapper.orderByDesc(Orders::getOrderTime);

        //SQL: SELECT * FROM orders WHERE number LIKE ? AND order_time BETWEEN ? AND ? ORDER BY order_time DESC LIMIT ?,?
        orderService.page(pageInfo, queryWrapper);

        //用户名处理 - 如何用户没有设置userName 则使用 收货人名称展示
        List<Orders> records = pageInfo.getRecords();
        for (Orders orders : records) {
            if (StringUtils.isEmpty(orders.getUserName())) {
                orders.setUserName(orders.getConsignee());
            }
        }
        pageInfo.setRecords(records);

        return R.success(pageInfo);
    }

    /**
     * 修改订单状态
     * @param orders
     * @return
     */
    @PutMapping
    public R update(@RequestBody Orders orders) {
        orderService.updateById(orders);
        return R.success("更新成功");
    }


    /**
     * 再来一单
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R again(@RequestBody Orders orders) {
        orderService.again(orders);
        return R.success("下单成功");
    }


}
